package zhongbo.java.air.monitor.web.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import zhongbo.java.air.monitor.config.RedisListenerConfig;
import zhongbo.java.air.monitor.listener.RedisLogChanelPublisher;
import zhongbo.java.air.monitor.mapper.FlightActivityDailyMapper;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/alert")
@Component
@Slf4j
public class AlertZoneWebSocket {

    public final static Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    private static RedisLogChanelPublisher redisLogChanelPublisher;
    private static RedisTemplate<String, Object> redisTemplate;

    private static FlightActivityDailyMapper flightActivityDailyMapper;

    @Autowired
    public AlertZoneWebSocket(RedisTemplate<String, Object> redisTemplate,
                              RedisLogChanelPublisher redisLogChanelPublisher,
                              FlightActivityDailyMapper flightActivityDailyMapper) {
        this.redisTemplate = redisTemplate;

        this.redisLogChanelPublisher = redisLogChanelPublisher;

        this.flightActivityDailyMapper = flightActivityDailyMapper;

    }
    public AlertZoneWebSocket() {

    }

    @OnOpen
    public void openConn(Session session) {
        String sessionId = session.getId();
        System.out.println("建立ws连接: " + sessionId);
        sessionMap.put(sessionId, session);
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        String sessionId = session.getId();
        String reasonPhrase = reason.getReasonPhrase();
        System.out.println(String.format("关闭ws连接: %s, reason: %s", sessionId, reasonPhrase));
        sessionMap.remove(sessionId);
    }


    @OnMessage
    public void echoTextMessage(Session session, String msg) {
        System.out.println("服务端收到消息:" + msg);
    }
    public static void broadcast(String msg) { // 发送至websocket前端页面
//            System.out.println("要发送的消息:" + msg);
            synchronized (sessionMap) {
                sessionMap.values().forEach(s -> {
                    try {
                        s.getBasicRemote().sendText(msg);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误：{}，Session ID： {}", error.getMessage(), session.getId());
        error.printStackTrace();
    }

}
